<template>
  <div style="padding: 20px;">
    <div class="topLocation">货物信息管理 / 货物管理</div>

    <!-- 搜索和操作按钮区域 -->
    <div class="topTool">
      <div class="group">货物名称：</div>
      <el-input v-model="searchName" placeholder="请输入货物名称" style="margin-right: 20px;"></el-input>
      <div class="group">货物类别：</div>
      <el-input v-model="searchCategory" placeholder="请输入货物类别" style="margin-right: 20px;"></el-input>
      <div class="group">所属仓库：</div>
      <el-input v-model="searchWarehouse" placeholder="请输入所属仓库" style="margin-right: 20px;"></el-input>
      <div class="group">所属人：</div>
      <el-input v-model="searchOwner" placeholder="请输入货物所属人" style="margin-right: 20px;"></el-input>

      <!-- 查询和添加按钮 -->
      <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
      <el-button type="success" :icon="Plus" @click="handleAdd">添加</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="goodsData" :header-cell-style="{ background: '#f6f9fa'}" @selection-change="handleSelectionChange"
              empty-text="暂无数据">
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="id" label="ID" sortable></el-table-column>
      <el-table-column prop="name" label="货物名称"></el-table-column>
      <el-table-column prop="category" label="货物类别"></el-table-column>
      <el-table-column prop="warehouseName" label="仓库名称"></el-table-column>
      <el-table-column prop="owner" label="货物所属人"></el-table-column>
      <el-table-column prop="stock" label="库存数量" sortable></el-table-column> <!-- 显示库存数量 -->
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <!-- 入库按钮 -->
          <el-button type="success" :icon="Plus" size="small" @click="handleStockIn(row)">入库</el-button>
          <!-- 出库按钮 -->
          <el-button type="warning" :icon="Delete" size="small" @click="handleStockOut(row)">出库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination background v-model:currentPage="currentPage" v-model:pageSize="pageSize" :page-sizes="[5, 10, 20]"
                   :total="total" layout="prev, pager, next, sizes" @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"></el-pagination>

    <!-- 添加货物的对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="50%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="货物名称">
          <el-input v-model="form.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="货物类别">
          <el-input v-model="form.category" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-input v-model="form.warehouseName" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="所属人">
          <el-input v-model="form.owner" :disabled="true" autocomplete="off" />
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input v-model="form.stock" type="number" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogOk">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted} from "vue";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit, Plus, Search} from "@element-plus/icons-vue";
import {useRoute} from "vue-router";

// 数据绑定
const goodsData = ref([]); // 货物数据
const currentPage = ref(1); // 当前页数
const pageSize = ref(5); // 每页显示条数
const total = ref(0); // 总记录数
const searchName = ref(''); // 货物名称搜索关键字
const searchCategory = ref(''); // 货物类别搜索关键字
const searchWarehouse = ref(''); // 仓库名称搜索关键字
const searchOwner = ref(''); // 所属人搜索关键字

// 选择的货物
let multipleSelection = ref([]);

// 获取数据
const getData = () => {
  axios.get('http://localhost:8080/goods/findByPage', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchName.value,
      category: searchCategory.value,
      warehouseName: searchWarehouse.value,
      owner: searchOwner.value
    }
  }).then(response => {
    goodsData.value = response.data.data.records;
    total.value = response.data.data.total;
  }).catch(error => {
    console.error(error);
  });
};

onMounted(() => {
  getData();
});

// 页码改变事件
const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  getData();
};

// 每页显示条数改变事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  getData();
};

// 查询按钮事件
const handleSearch = () => {
  // 获取四个搜索框的值
  const params = {
    name: searchName.value || null,        // 货物名称
    category: searchCategory.value || null,  // 货物类别
    warehouseName: searchWarehouse.value || null,  // 所属仓库
    owner: searchOwner.value || null       // 所属人
  };

  // 发送请求，查询货物
  axios.get('http://localhost:8080/goods/search', {params})
      .then(response => {
        goodsData.value = response.data.data;  // 更新数据
      })
      .catch(error => {
        console.error(error);
        ElMessage.error('查询失败');
      });
};

const route = useRoute();
const operatorName = route.query.name || ''; // 获取 name

// 入库按钮事件
const handleStockIn = (row) => {
  // 检查所属人是否与当前登录用户一致
  if (row.owner !== operatorName) {
    ElMessage.error('您没有权限进行此操作');
    return;
  }

  // 弹出对话框让用户输入入库数量
  ElMessageBox.prompt('请输入入库数量', '入库操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[1-9][0-9]*$/, // 输入正整数
    inputErrorMessage: '请输入有效的正整数数量'
  }).then(({ value }) => {
    const quantity = parseInt(value, 10);
    if (quantity > 0) {
      // 弹出对话框让用户输入备注
      ElMessageBox.prompt('请输入备注', '入库备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(?!\s*$).+$/,  // 确保备注不能为空，不能只含有空格
        inputErrorMessage: '请输入备注内容'
      }).then(({ value }) => {
        let remark = value.trim();  // 获取备注并去除前后空格
        // 执行入库操作
        axios.post(`http://localhost:8080/goods/in?goodsName=${row.name}&warehouseName=${row.warehouseName}&quantity=${quantity}&category=${row.category}`)
            .then((response) => {
              if (response.data.code === 1) {  // 成功
                ElMessage.success(`货物【${row.name}】入库成功!`);
                row.stock += quantity;  // 更新本地库存
                // 保存入库记录
                axios.post('http://localhost:8080/record', {
                  goodsName: row.name,
                  warehouseName: row.warehouseName,
                  category: row.category,
                  operator: operatorName, // 从前端获取操作人信息
                  applicant: row.owner, // 从前端获取申请人信息（所属人）
                  actionType: '入库',
                  quantity: quantity,
                  remark: remark // 使用用户输入的备注
                }).then(() => {
                  getData();  // 重新加载数据
                }).catch((error) => {
                  console.error(error);
                  ElMessage.error('保存入库记录失败');
                });
              } else {
                ElMessage.error(response.data.msg || '入库失败');
              }
            }).catch((error) => {
          console.error(error);
          ElMessage.error('入库失败');
        });
      }).catch(() => {
        ElMessage.info('取消备注输入');
      });
    } else {
      ElMessage.error('数量必须大于0');
    }
  }).catch(() => {
    ElMessage.info('取消入库操作');
  });
};

// 出库按钮事件
const handleStockOut = (row) => {
  // 检查所属人是否与当前登录用户一致
  if (row.owner !== operatorName) {
    ElMessage.error('您没有权限进行此操作');
    return;
  }

  // 弹出对话框让用户输入出库数量
  ElMessageBox.prompt('请输入出库数量', '出库操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[1-9][0-9]*$/, // 输入正整数
    inputErrorMessage: '请输入有效的正整数数量'
  }).then(({ value }) => {
    const quantity = parseInt(value, 10);
    if (quantity > 0) {
      if (row.stock >= quantity) {
        // 弹出对话框让用户输入备注
        ElMessageBox.prompt('请输入备注', '出库备注', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^(?!\s*$).+$/,  // 确保备注不能为空，不能只含有空格
          inputErrorMessage: '请输入备注内容'
        }).then(({ value }) => {
          let remark = value.trim();  // 获取备注并去除前后空格
          // 执行出库操作
          axios.post(`http://localhost:8080/goods/out?goodsName=${row.name}&warehouseName=${row.warehouseName}&quantity=${quantity}&category=${row.category}`)
              .then((response) => {
                if (response.data.code === 1) {  // 成功
                  ElMessage.success(`货物【${row.name}】出库成功!`);
                  row.stock -= quantity;  // 更新本地库存
                  // 保存出库记录
                  axios.post('http://localhost:8080/record', {
                    goodsName: row.name,
                    warehouseName: row.warehouseName,
                    category: row.category,
                    operator: operatorName, // 从前端获取操作人信息
                    applicant: row.owner, // 从前端获取申请人信息（所属人）
                    actionType: '出库',
                    quantity: quantity,
                    remark: remark // 使用用户输入的备注
                  }).then(() => {
                    getData();  // 重新加载数据
                  }).catch((error) => {
                    console.error(error);
                    ElMessage.error('保存出库记录失败');
                  });
                } else {
                  ElMessage.error(response.data.msg || '出库失败');
                }
              }).catch((error) => {
            console.error(error);
            ElMessage.error('出库失败');
          });
        }).catch(() => {
          ElMessage.info('取消备注输入');
        });
      } else {
        ElMessage.error('库存不足');
      }
    } else {
      ElMessage.error('数量必须大于0');
    }
  }).catch(() => {
    ElMessage.info('取消出库操作');
  });
};

// 选择变化事件
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map(item => item.id);
};

// 弹窗表单数据绑定
const dialogFormVisible = ref(false);
const dialogTitle = ref('添加货物');
const form = ref({
  id: null,
  name: '',
  category: '',
  warehouseName: '',
  owner: operatorName, // 设置所属人字段为 router 中的 name 参数
  stock: 0
});

const dialogOk = () => {
  // 检查必填项
  if (!form.value.name || !form.value.category || !form.value.warehouseName || !form.value.owner || form.value.stock <= 0) {
    ElMessage.error('所有字段都必须填写并且库存大于0');
    return;
  }
  // 添加货物请求
  axios.post('http://localhost:8080/goods', form.value)
      .then((response) => {
        if (response.data.code === 1) {
          dialogFormVisible.value = false;
          getData();
          ElMessage.success('添加成功!');
        } else {
          ElMessage.error(response.data.msg || '添加失败');
        }
      })
      .catch((error) => {
        console.error(error);
        ElMessage.error(error.response?.data?.msg || '请求失败，请稍后再试');
      });
}

// 添加按钮事件
const handleAdd = () => {
  dialogTitle.value = '添加货物';
  form.value = { id: null, name: '', category: '', warehouseName: '', owner: operatorName, stock: 0 };  // 在这里设置所属人
  dialogFormVisible.value = true;
};


</script>

<style scoped>
.topLocation {
  font-size: 16px;
  font-weight: bold;
  color: #000; /* 文字颜色为黑色 */
  padding: 10px;
  border-bottom: 2px solid #000; /* 底部边框，黑色 */
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-start; /* 左对齐 */
  margin-bottom: 20px; /* 增加距离 */
}

.topTool {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.group {
  white-space: nowrap; /* 防止文字换行 */
  font-size: 14px; /* 设置字体大小为 14px */
}

.button-row {
  display: flex;
  gap: 10px;
  justify-content: flex-start;
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>